//
//  WordFollowViewController.m
//  Learn
//
//  Created by chijianguo on 2024/4/10.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "WordFollowViewController.h"
#import "TestFinishViewController.h"
#import "HomeRequest.h"
#import "WordActionCell.h"
#import "WordContentCell.h"
#import "WordProgressCell.h"
#import "PlayManager.h"
#import "SubmitWorkViewController.h"
#import "RecordHelper.h"
#import "PcmPlayer.h"

typedef enum : NSUInteger {
    ActionStateReady,       // 初始化
    ActionStateLession,     // 播放资源音频
    ActionStateStartRecord, // 开始评测
    ActionStateEndRecord,   // 结束评测，
} ActionState;

@interface WordFollowViewController ()<UITableViewDelegate, UITableViewDataSource,IFlyDetectionDelegate,PlayManagerDelegate>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSString *baseUrl;

@property (nonatomic,strong) IFlyDetection *detection;//评测对象
@property (nonatomic,strong) RecordHelper *recordHelper;
@property (nonatomic, strong) PcmPlayer *pcmPlay;
@property (nonatomic, strong) PlayManager *player;

@property (nonatomic , assign)BOOL isAutomatic; // 是否自动
@property (nonatomic , assign)ActionState actionState;

@property (nonatomic, assign) NSUInteger currentIndex;

@end

@implementation WordFollowViewController

- (void)back {
    [self.detection cancle];
    [self.player pause];
    [self.recordHelper stopRecord];
    [self.pcmPlay stop];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.recordHelper = [[RecordHelper alloc] init];
    self.player = [PlayManager sharPlayManager];
    self.player.delegate = self;
    self.detection.delegate = self;
    [self.detection evalutType:1];
    [self.detection evalutLanguage:1];
    
    [self setUI];
    [self setNavUI];
    [self loadData];
}

- (void)loadData {
    [HomeRequest getTextBookWordInfoWithId:self.unitWordModel.versionId moduleId:self.unitWordModel.moduleId Result:^(TextBookUnitSourceListModel *list) {
        self.baseUrl = list.resmain;
        self.dataArr = list.wordResource;
        self.currentIndex = 0;
        self.actionState = ActionStateReady;
        DebugLog(@"%@",list);
        [self.tableView reloadData];
    }];
}

- (void)setUI {
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,NavigationBarHeight, SCREEN_W, SCREEN_H - NavigationBarHeight - SafeAreaBottomHeight) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    if (@available(iOS 13.0, *)) {
        [self.tableView setAutomaticallyAdjustsScrollIndicatorInsets:NO];
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.tableView.backgroundColor=[UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"WordProgressCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"WordProgressCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WordContentCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"WordContentCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WordActionCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"WordActionCell"];

}

- (void)setNavUI {
    UIView *nav = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, NavigationBarHeight)];
    nav.backgroundColor = rgba(245, 245, 245, 1);
    [self.view addSubview:nav];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [nav addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nav.mas_left).offset(5);
        make.bottom.equalTo(nav.mas_bottom);
        make.width.offset(50);
        make.height.offset(44);
    }];
    
    UILabel *titleL = [[UILabel alloc] init];
    titleL.text = self.unitWordModel.moduleName;
    titleL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    titleL.textColor = rgb(51, 51, 51);
    titleL.textAlignment = NSTextAlignmentCenter;
    [nav addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(nav.mas_bottom);
        make.centerX.equalTo(nav.mas_centerX);
        make.height.offset(44);
    }];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0){
        return 60;
    }
    if(indexPath.row == 1){
        return SCREEN_H - NavigationBarHeight - SafeAreaBottomHeight-120-60;
    }
    if(indexPath.row == 2){
        return 120;
    }

    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        WordProgressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WordProgressCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"WordProgressCell" owner:self options:nil] lastObject];
        }
        cell.changeBlock = ^(NSUInteger value) {
            self.isAutomatic = value==1;
        };
        cell.currentIndexLB.text = [NSString stringWithFormat:@"%lu",(unsigned long)self.currentIndex+1];
        cell.allCountLB.text = [NSString stringWithFormat:@"/%lu",(unsigned long)self.dataArr.count];
        cell.progressView.progress = self.dataArr.count==0 ? 0 : self.currentIndex*1.0/self.dataArr.count;
        return cell;
    }
    if(indexPath.row == 1){
        WordContentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WordContentCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"WordContentCell" owner:self options:nil] lastObject];
        }
        TextBookUnitWordModel *currentModel = self.dataArr[self.currentIndex];
        NSString *imurl = [NSString stringWithFormat:@"%@%@",self.baseUrl,currentModel.wordPic];
        [cell.imView sd_setImageWithURL:[NSURL URLWithString:imurl] placeholderImage:[UIImage imageNamed:@""]];
        cell.titleLB.text = currentModel.words;
        cell.subTitleLB.text = [NSString stringWithFormat:@"%@\n%@",currentModel.pretations,currentModel.symbol];
        cell.sentencesLB.text = currentModel.sentences;
        cell.model = currentModel;
        return cell;
    }
    if(indexPath.row == 2){
        WordActionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WordActionCell" forIndexPath:indexPath];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"WordActionCell" owner:self options:nil] lastObject];
        }
        cell.recordBlock = ^{
        };
        cell.lessonBlock = ^{
        };
        cell.playBlock = ^{
            [self play];
        };

        cell.preBlock = ^{
            [self pre];
        };

        cell.nextBlock = ^{
            [self next];
        };
        
        TextBookUnitWordModel *currentModel = self.dataArr[self.currentIndex];
        cell.wordModel = currentModel;
        return cell;
    }

    return nil;
}

- (void)setActionState:(ActionState)actionState {
    if (actionState == ActionStateReady) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.actionState = ActionStateLession;
        });
    }
    
    if (actionState == ActionStateLession) {
        [self showLoadingViewWithText:nil];
        TextBookUnitWordModel *currentModel = self.dataArr[self.currentIndex];
        NSString *url = [NSString stringWithFormat:@"%@%@",self.baseUrl,currentModel.wordFile];
        [self.player playerWithURL:url];
        NSUInteger time = [self.player getDurationWithUrlString:url];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.actionState = ActionStateStartRecord;
        });
    }
    
    if (actionState == ActionStateStartRecord) {
        [self recordWord];
    }
    
    if (actionState == ActionStateEndRecord) {
        if(!self.isAutomatic){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self next];
            });
        }
    }

}

- (void)changeModel {
    [self.player pause];
    [self.recordHelper stopRecord];
    [self.detection stop];
    [self.pcmPlay stop];
}

// 下一个
- (void)next {
    [self changeModel];
    
    if(self.currentIndex == self.dataArr.count-1){
        DebugLog(@"============最后一个");
        SubmitWorkViewController *vc = [[SubmitWorkViewController alloc] init];
        vc.unitWordModel = self.unitWordModel;
        vc.type = @"单词";
        vc.dataArr = self.dataArr;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    self.currentIndex = self.currentIndex+1;
    self.actionState = ActionStateReady;
    [self.tableView reloadData];
}

// 上一个
- (void)pre {
    [self changeModel];

    if(self.currentIndex == 0){
        DebugLog(@"============第一个");
        return;
    }
    self.currentIndex = self.currentIndex-1;
    self.actionState = ActionStateReady;
    [self.tableView reloadData];
}

// 播放自己录音
- (void)play {
    [self changeModel];

    TextBookUnitWordModel *currentModel = self.dataArr[self.currentIndex];
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:currentModel.recordPath]) {
        [HomeRequest upLoadAudioWithPath:currentModel.recordPath result:^(NSDictionary *url) {
            if (!IsStrEmpty(url[@"fullurl"])) {
                TextBookUnitWordModel *model = self.dataArr[self.currentIndex];
                model.recordUrl = url[@"fullurl"];
            }
        }];
        self.pcmPlay = [[PcmPlayer alloc] initWithFilePath:currentModel.recordPath sampleRate:8000];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.pcmPlay play];
        });
    }
}

- (void)lesson {
    [self changeModel];

    [self showLoadingViewWithText:nil];
    TextBookUnitWordModel *currentModel = self.dataArr[self.currentIndex];
    NSString *imurl = [NSString stringWithFormat:@"%@%@",self.baseUrl,currentModel.wordFile];
    [self.player playerWithURL:imurl];

}

- (void)recordWord {
    [self changeModel];

    //开始录音
    void(^StartSpeakingVoice)(void) = ^() {
        TextBookUnitWordModel *currentModel = self.dataArr[self.currentIndex];
        [self.detection startEvalutingWord:[NSString stringWithFormat:@"%@",currentModel.words]];

        [self.recordHelper startRecord:currentModel.recordPath];
    };
    
    //检测是否授权麦克风
    void(^CheckOutAuthorization)(void) = ^() {
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
            //第一次询问用户是否进行授权
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                if (granted) {
                    StartSpeakingVoice();
                }
            }];
        }
        else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {// 未授权
            NSString *message = @"\n麦克风权限未开启，请进入系统【设置】>【隐私】>【麦克风】中打开开关,开启麦克风功能";
            [self alertViewTitle:@"麦克风权限未开启" message:message left:@"确定" leftBlock:^{
                
            } right:@"前往" rightBlock:^{
                //跳入当前App设置界面
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
        }
        else{// 已授权
            StartSpeakingVoice();
        }
    };
    
    CheckOutAuthorization();

}

#pragma mark - PlayManagerDelegate
- (void)musicFinsh {
    DebugLog(@"===========");
}
- (void)playStateChange:(AVPlayerItemStatus)state {
    [self removeLoadingView];
}

#pragma mark - IFlyDetectionDelegate
- (void)evaluting:(IFlyDetection *)ifyldetection result:(NSString *)result {
    
    //评测分数
    CGFloat totalScore = 0;
    NSArray<NSString*> *words = [result componentsSeparatedByString:@"\n"];
    for (NSString *obj in words) {
        NSString *searchWord = @"Total Score：";
        if ([obj containsString:searchWord]) {
            totalScore = [[obj substringFromIndex:searchWord.length] floatValue];
        }
    }
    DebugLog(@"评测结果: %@ == %f",result,totalScore);
    TextBookUnitWordModel *currentModel = self.dataArr[self.currentIndex];
    currentModel.isRead = YES;
    currentModel.totalScore = totalScore;
    currentModel.completionDegree = totalScore;
    currentModel.accurateDegree = totalScore;
    currentModel.fluentDegree = totalScore;
    [self.tableView reloadData];
    
    self.actionState = ActionStateEndRecord;
    
}

- (IFlyDetection *)detection {
    if (!_detection) {
        _detection = [[IFlyDetection alloc] init];
    }
    return _detection;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

@end
